import {useRef, useState} from 'react';
import {AES, enc, mode, pad} from 'crypto-js';
import {RSA_IV, RSA_KEY, SERVER_BASE_URL} from 'root/constant';
import SendPool from '@/utils/SendPool.ts';

// 发送线程池，设置每次同时发送的数量
const sendPool = new SendPool(3);

function useContainer() {
  const [updatePercent, setUpdatePercent] = useState<number>();
  const [finishList, setFinishList] = useState<string[]>([]);

  const inputRef = useRef<HTMLInputElement>(null);

  const handleClick = async () => {
    const file = inputRef.current.files[0];

    if (!file) {
      alert('先选择文件');
      return;
    }

    setUpdatePercent(0);

    const base64 = await new Promise(resolve => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => {
        const base64 = reader.result;
        resolve(base64);
      };
    });

    // 总文件
    const totalData = AES.encrypt(base64 as string, enc.Utf8.parse(RSA_KEY), {
      iv: enc.Utf8.parse(RSA_IV),
      mode: mode.CBC,
      padding: pad.Pkcs7,
    }).toString();
    const fileName = file.name;

    // 文件分片, 100KB一片
    const size = 1024 * 100;
    // 计算分片总数量
    const totalCount = Math.ceil(totalData.length / size);
    // 数据分片列表
    const data: string[] = [];
    // 执行分片操作
    for (let i = 0; i < totalCount; i++) {
      data[i] = totalData.slice(i * size, (i + 1) * size);
    }
    // 将分片数据包装为表单数据
    const tasks = data.map((data, index) => {
      const form = new FormData();
      form.set('data', data);
      form.set('filename', fileName);
      form.set('index', `${index}`);
      form.set('total', `${totalCount}`);

      return updateFile.bind(null, form);
    });

    // 设置任务队列
    sendPool.setQueue(tasks);
    // 开始上传
    sendPool.start((finishTotal, total) => {
      setUpdatePercent(Math.floor(finishTotal * 100 / total));

      if (finishTotal === total) {
        setFinishList((prev) => [...prev, fileName]);
        inputRef.current.value = '';
        setUpdatePercent(undefined);
        setTimeout(() => alert('上传成功'));
      }
    });
  };

  return {handleClick, updatePercent, inputRef, finishList};
}

export default function Home() {
  const {handleClick, updatePercent, inputRef, finishList} = useContainer();

  return (
    <>
      <h1>欧尼酱的银窝</h1>
      已上传成功的图片：
      <ul id="res">
        {
          finishList.length ? finishList?.map((item, i) => (
            <li key={i}>{item}</li>
          )) : '暂无'
        }
      </ul>
      <form id="form">
        <input ref={inputRef} disabled={updatePercent !== undefined} id="file"
               type="file" name="file"/>
      </form>
      <button style={{marginTop: '20px'}} id="submit"
              disabled={updatePercent !== undefined}
              onClick={handleClick}>{updatePercent === undefined ? '提交' : `当前已上传: ${updatePercent}%`}</button>
    </>
  );
}

function updateFile(formData: FormData) {
  return fetch(SERVER_BASE_URL + '/file', {
    method: 'POST',
    body: formData,
  });
}